﻿using System.IO;
using System.Xml;
using System;

namespace Toybox.NicoSharp.Video
{
	using Message;

	public partial class ChatCreator
	{

		#region Constructor

		public ChatCreator(Flv flv, Thread thread)
		{
			this.Thread = thread.thread;
			this.Ticket = thread.ticket;

			this.UserId = flv.user_id;
			this.Premium = flv.is_premium;

			this.ChatPostKey = new PostKey(this.Thread, flv.Cookies);
		}

		#endregion Constructor


		#region Public Members

		public string Thread
		{
			get;
			protected set;
		}

		public string Ticket
		{
			get;
			protected set;
		}

		public string UserId
		{
			get;
			protected set;
		}

		public PremiumType Premium
		{
			get;
			protected set;
		}


		public int LastRes
		{
			get;
			set;
		}


		public int VPos
		{
			get;
			set;
		}

		public string Mail
		{
			get;
			set;
		}

		public string Content
		{
			get;
			set;
		}

		#endregion Public Members

		#region Protected Members

		protected PostKey ChatPostKey
		{
			get;
			set;
		}

		#endregion Protected Members


		#region Public Methods

		public void UpdateKey()
		{
			int blockNo = (this.LastRes + 1) / 100;
			if (this.ChatPostKey.BlockNo != blockNo)
			{
				this.ChatPostKey.BlockNo = blockNo;
				this.ChatPostKey.Update();
			}
		}

		public override string ToString()
		{
			if (string.IsNullOrEmpty(this.Content))
				throw new ArgumentNullException("Content");

			XmlDocument doc = new XmlDocument();
			doc.AppendChild(doc.CreateElement("chat"));

			this.CreateDocument(ref doc);

			try
			{
				using (var sw = new StringWriter())
				using (var tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					return sw.ToString();
				}
			}
			catch
			{
				return null;
			}
		}

		#endregion Public Methods

		#region Protected Methods

		protected virtual void CreateDocument(ref XmlDocument doc)
		{
			XmlElement root = doc.DocumentElement;
			root.SetAttribute("thread", this.Thread);
			root.SetAttribute("vpos", this.VPos.ToString());
			root.SetAttribute("mail", this.Mail);
			root.SetAttribute("ticket", this.Ticket);
			root.SetAttribute("user_id", this.UserId);
			root.SetAttribute("postkey", this.ChatPostKey.Value);

			if (this.Premium != PremiumType.Normal)
				root.SetAttribute("premium", ((int)this.Premium).ToString());

			root.InnerText = this.Content;
		}

		#endregion Protected Methods

	}
}
